package cn.chiship.framework.business.biz.business.controller;


import cn.chiship.framework.common.annotation.SystemOptionAnnotation;
import cn.chiship.framework.common.enums.BusinessTypeEnum;
import cn.chiship.sdk.core.annotation.RequiredPermissions;
import cn.chiship.sdk.core.annotation.RequiredRoles;
import cn.chiship.sdk.core.enums.PermissionsEnum;
import cn.chiship.sdk.core.util.*;
import cn.chiship.sdk.framework.base.BaseService;
import cn.chiship.sdk.framework.base.BaseController;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.annotation.Authorization;

import javax.annotation.Resource;

import cn.chiship.framework.business.biz.business.service.TestExampleService;
import cn.chiship.framework.business.biz.business.entity.TestExample;
import cn.chiship.framework.business.biz.business.entity.TestExampleExample;
import cn.chiship.framework.business.biz.business.pojo.dto.TestExampleDto;
import io.swagger.annotations.*;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 示例（正式环境可删除）控制层
 * 2022/9/15
 *
 * @author lijian
 */
@RestController
@Authorization
@RequestMapping("/testExample")
@Api(tags = "示例（正式环境可删除）")
public class TestExampleController extends BaseController<TestExample, TestExampleExample> {

    private static final Logger LOGGER = LoggerFactory.getLogger(TestExampleController.class);

    @Resource
    private TestExampleService testExampleService;

    @Override
    public BaseService getService() {
        return testExampleService;
    }

    @ApiOperation(value = "测试是否拥有指定权限")
    @GetMapping("/permissions1")
    @Authorization
    @RequiredPermissions({"deleted"})
    @RequiredRoles({"ddddd"})
    public ResponseEntity<BaseResult> permissions1() {
        return new ResponseEntity<>(BaseResult.ok(), HttpStatus.OK);
    }

    @ApiOperation(value = "测试是否拥有指定权限")
    @GetMapping("/permissions2")
    @Authorization
    @RequiredPermissions(value = {"deleted", "updated"}, logical = PermissionsEnum.OR)
    public ResponseEntity<BaseResult> permissions2() {
        return new ResponseEntity<>(BaseResult.ok(), HttpStatus.OK);
    }

    @SystemOptionAnnotation(describe = "示例（正式环境可删除）分页")
    @ApiOperation("示例（正式环境可删除）分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", example = "1", required = true, dataTypeClass = Long.class, paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "每页条数", example = "10", required = true, dataTypeClass = Long.class, paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序方式", example = "-gmtModified", dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键字", dataTypeClass = String.class, paramType = "query"),
    })
    @GetMapping(value = "/page")
    public ResponseEntity<BaseResult> page(@RequestParam(required = false, defaultValue = "", value = "keyword") String keyword) {
        TestExampleExample testExampleExample = new TestExampleExample();
        //创造条件
        TestExampleExample.Criteria testExampleCriteria = testExampleExample.createCriteria();
        testExampleCriteria.andIsDeletedEqualTo(BaseConstants.NO);
        if (!StringUtil.isNullOrEmpty(keyword)) {
            testExampleCriteria.andNameLike(keyword + "%");

        }
        return super.responseEntity(BaseResult.ok(super.page(testExampleExample)));
    }

    @SystemOptionAnnotation(describe = "示例（正式环境可删除）列表数据")
    @ApiOperation("示例（正式环境可删除）列表数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", value = "关键字", dataTypeClass = String.class, paramType = "query"),
    })
    @GetMapping(value = "/list")
    public ResponseEntity<BaseResult> list(@RequestParam(required = false, defaultValue = "", value = "keyword") String keyword) {
        TestExampleExample testExampleExample = new TestExampleExample();
        //创造条件
        TestExampleExample.Criteria testExampleCriteria = testExampleExample.createCriteria();
        testExampleCriteria.andIsDeletedEqualTo(BaseConstants.NO);
        if (!StringUtil.isNullOrEmpty(keyword)) {
            testExampleCriteria.andNameLike(keyword + "%");

        }
        return super.responseEntity(BaseResult.ok(super.list(testExampleExample)));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_SAVE, describe = "保存示例（正式环境可删除）")
    @ApiOperation("保存示例（正式环境可删除）")
    @PostMapping(value = "save")
    public ResponseEntity<BaseResult> save(@RequestBody @Valid TestExampleDto testExampleDto) {
        TestExample testExample = new TestExample();
        BeanUtils.copyProperties(testExampleDto, testExample);
        return super.responseEntity(super.save(testExample));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_UPDATE, describe = "更新示例（正式环境可删除）")
    @ApiOperation("更新示例（正式环境可删除）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", dataTypeClass = String.class, paramType = "path", required = true)
    })
    @PostMapping(value = "update/{id}")
    public ResponseEntity<BaseResult> update(@PathVariable("id") String id, @RequestBody @Valid TestExampleDto testExampleDto) {
        TestExample testExample = new TestExample();
        BeanUtils.copyProperties(testExampleDto, testExample);
        return super.responseEntity(super.update(id, testExample));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_REMOVE, describe = "删除示例（正式环境可删除）")
    @ApiOperation("删除示例（正式环境可删除）")
    @PostMapping(value = "remove")
    public ResponseEntity<BaseResult> remove(@RequestBody @Valid List<String> ids) {
        TestExampleExample testExampleExample = new TestExampleExample();
        testExampleExample.createCriteria().andIdIn(ids);
        return super.responseEntity(super.remove(testExampleExample));
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_UPDATE, describe = "生成PDF（正式环境可删除）")
    @ApiOperation("生成PDF（正式环境可删除）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", dataTypeClass = String.class, paramType = "path"),
    })
    @PostMapping(value = "generatePdf/{id}")
    public void generatePdf(@PathVariable("id") String id,
                            HttpServletResponse response) throws Exception {

        TestExample testExample = testExampleService.selectByPrimaryKey(id);
        Map<String, Object> reportData = new HashMap<>(7);
        reportData.put(PdfUtil.PDF_TEMPLATE_FIELD_TYPE_TEXT + "regionName", testExample.getName());
        reportData.put(PdfUtil.PDF_TEMPLATE_FIELD_TYPE_TEXT + "firstLetter", testExample.getFirstLetter());
        reportData.put(PdfUtil.PDF_TEMPLATE_FIELD_TYPE_TEXT + "adCode", testExample.getAdCode());
        reportData.put(PdfUtil.PDF_TEMPLATE_FIELD_TYPE_TEXT + "fullPingYin", testExample.getFullPinyin());
        reportData.put(PdfUtil.PDF_TEMPLATE_FIELD_TYPE_TEXT + "remrk", "山东省（Shandong）是中国华东地区的一个沿海省份，简称鲁，省会济南。位于中国东部沿海北纬34°22.9′-38°24.01′，东经114°47.5′-122°42.3′之间，自北而南与河北、河南、安徽、江苏4省接壤。 [22]  山东东西长721.03千米，南北长437.28千米，全省陆域面积15.58万平方千米。 [7]  2021年山东省的常住人口为10169.99万人，比上年增加了17.24万人。");

        reportData.put(PdfUtil.PDF_TEMPLATE_FIELD_TYPE_IMAGE + "image", ImageUtil.getImgByteByUrl("https://cdn-chiship.oss-cn-beijing.aliyuncs.com/default/testPdfImage.png"));
        reportData.put(PdfUtil.PDF_TEMPLATE_FIELD_TYPE_TEXT + "fillDate", DateUtils.getTime());
        byte[] bytes = PdfUtil.generalPdfByTemplateInput(FileUtil.downLoadToByte("https://cdn-chiship.oss-cn-beijing.aliyuncs.com/default/pdfTemplate.pdf"), reportData);

        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");


        IOUtils.write(bytes, response.getOutputStream());


    }
}